package com.shunhao.utils

import android.os.Handler
import android.widget.TextView

/**
 * 倒计时的CodeTimer
 *
 * @author 康贵阳
 */
class CodeTimer(private val codeTv: TextView) {

    /**
     * 倒计时时间60s
     */
    private var time = 60

    private var timerHandler: Handler? = null

    private var timerRunnable: Runnable? = null

    init {
        initTimer()
    }

    private fun initTimer() {
        timerHandler = Handler()
        timerRunnable = Runnable {
            time--
            if (time == 0) {
                timerHandler!!.removeCallbacks(timerRunnable!!)
                codeTv.isEnabled = true
                time = 60
                codeTv.text = codeTv.context.getString(R.string.hint_get_sms_code)
            } else {
                val time = "重新获取 ${time}秒"
                codeTv.text = time
                timerHandler?.postDelayed(timerRunnable!!, 1000)
            }
        }
    }

    fun startTimer() {
        codeTv.isEnabled = false
        val showTime = "重新获取 ${time}秒"
        codeTv.text = showTime
        timerHandler!!.removeCallbacks(timerRunnable!!)
        timerHandler!!.postDelayed(timerRunnable!!, 1000)
    }

    fun stopTimer() {
        time = 60
        codeTv.isEnabled = true
        codeTv.text = codeTv.context.getString(R.string.hint_get_sms_code)
        timerHandler!!.removeCallbacks(timerRunnable!!)
        timerHandler!!.removeCallbacksAndMessages(null)
    }


}